﻿using SmartSpace.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace SmartSpace.WebApp.Template.Prototype
{
    public partial class HeaderPanel : System.Web.UI.UserControl, IHeaderPanel
    {
        public Core.User SsUser { get; private set; }
        public event LogoffEventHandler Logoff;

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public void Initiate(IEnumerable<Core.Nav> navigations, IEnumerable<Core.Shortcut> shortcuts, List<Core.Site> applications, Core.Site curSite, Core.User loginUser)
        {
            SsUser = loginUser;
            _ctlTextTitle.InnerText = curSite.Name;
            _ctlLinkUser.InnerText = string.Format("{0}({1})", loginUser.Prefix, loginUser.Name);

            foreach (var item in shortcuts)
            {
                HtmlGenericControl ctlLink = new HtmlGenericControl("a");
                ctlLink.InnerText = item.Caption;
                ctlLink.Attributes.Add("href", ConvertUrl(item));
                this._ctlShortcutContainer.Controls.Add(ctlLink);
            }
        }

        private string ConvertUrl(Core.Shortcut shortcut)
        {
            string url = shortcut.Url;
            if (url.StartsWith("~"))
            {
                return this.ResolveClientUrl(url);
            }
            return url;
        }

        private string ConvertUrl(Core.Nav nav)
        {
            if (string.IsNullOrEmpty(nav.Url))
            {
                return "";
            }
            else
            {
                string url = nav.Url;
                if (url.StartsWith("~"))
                {
                    return this.ResolveClientUrl(url);
                }
                return url;
            }
        }

        protected void _ctlBtnLogoff_Click(object sender, EventArgs e)
        {
            if (Logoff != null)
            {
                Logoff(this, new LogoffEventArgs(SsUser));
            }
        }
    }
}